<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付信息管理</title>
    <link rel="stylesheet" href="../layui/css/layui.css">
		<script src="../js/authChecker.js"></script>
    <style>
        .payinfo-container {
            padding: 20px;
        }

        .payinfo-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .payinfo-table th,
        .payinfo-table td {
            border: 1px solid #ccc;
            padding: 10px;
            text-align: center;
        }

        .payinfo-table th {
            background-color: #d8d8d9;
            color: black;
            font-weight: bold;
        }

        .payinfo-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .payinfo-table tr:hover {
            background-color: #f1f1f1;
        }

        .payinfo-table td:nth-child(5),
        .payinfo-table td:nth-child(6),
        .payinfo-table td:nth-child(7),
        .payinfo-table td:nth-child(9) {
            text-align: right;
            font-family: monospace;
        }

        .search-area {
            background: #fff;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .layui-card-header {
            font-size: 22px;
            color: #333;
            margin-bottom: 20px;
            font-weight: 600;
        }

        .delivery-status-0 {
            color: #009688;
        }

        .delivery-status-1 {
            color: #fcfbfa;
        }

        .money-discount {
            color: #FFB800;
            font-weight: bold;
        }

        .action-buttons {
            display: flex;
            justify-content: center;
            gap: 5px;
        }

        .delete-btn {
            background-color: #fbfaf9 !important;
            border: 1px solid black;
            color: black !important;
        }

        .remark-btn {
            background-color: #fbfaf9 !important;
            border: 1px solid black;
            color: black !important;
        }

        .remark-dialog {
            padding: 20px;
        }

        .error-message {
            color: #FF5722;
            margin-top: 5px;
            font-size: 12px;
        }
        .layui-btn-normal{
            background-color: #fbfaf9 !important;
            border: 1px solid black;
            color: black !important;
        }
    </style>
</head>

<body>
    <div class="payinfo-container">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-header">支付信息管理</div>
                    <div class="layui-card-body">
                        <!-- 搜索区域 -->
                        <div class="search-area">
                            <form class="layui-form" lay-filter="searchForm">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">订单号</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="orderNum" placeholder="请输入订单号" autocomplete="off"
                                                class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">地址</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="address" placeholder="请输入地址关键词" autocomplete="off"
                                                class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">蛋糕名称</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="cakeName" placeholder="请输入蛋糕名称" autocomplete="off"
                                                class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="searchBtn">
                                            <i class="layui-icon">&#xe615;</i> 搜索
                                        </button>
                                        <button type="reset" class="layui-btn layui-btn-primary" id="resetBtn">
                                            <i class="layui-icon">&#xe669;</i> 重置
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 支付信息表格 -->
            <table class="payinfo-table" id="payinfoTable">
                <thead>
                    <tr>
                        <th>支付ID</th>
                        <th>订单号</th>
                        <th>地址</th>
                        <th>蛋糕名称</th>
                        <th>配送费</th>
                        <th>优惠金额</th>
                        <th>备注</th>
                        <th>实付金额</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 动态内容将通过JS填充 -->
                </tbody>
            </table>

            <!-- 分页 -->
            <div id="payinfoPage" style="text-align: right; margin-top: 15px;"></div>
        </div>
    </div>

    <!-- 备注修改对话框 -->
    <div id="remarkDialog" style="display: none;">
        <form class="layui-form remark-dialog" lay-filter="remarkForm">
            <input type="hidden" name="payid">
            <div class="layui-form-item">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="remarkSubmit">保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                    <div class="error-message" id="remarkError" style="display: none;"></div>
                </div>
            </div>
        </form>
    </div>

    <script src="../layui/layui.js"></script>
    <script>
		// 在页面加载时立即检查登录状态
		        if (!checkAdminLogin()) {
		            // 登录检查失败，阻止页面继续加载
		            console.log('登录验证失败，已跳转至登录页');
		        } else {
        layui.use(['form', 'layer', 'laypage', 'table'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var laypage = layui.laypage;
            var $ = layui.$;
            var table = layui.table;

            // 当前页码和每页条数
            var currentPage = 1;
            var pageSize = 10;

            // 搜索条件
            var searchParams = {};

            // 加载支付信息
            function loadPayInfos() {
                layer.load(1);

                // 合并搜索参数
                var params = $.extend({
                    pageNum: currentPage,
                    pageSize: pageSize
                }, searchParams);

                $.ajax({
                    url: 'http://localhost:8887/orderpayinfo/selectOrderpayinfo',
                    type: 'GET',
                    data: params,
                    success: function (res) {
                        layer.closeAll('loading');

                        if (res && res.code === 200 && res.data && res.data.Orderpayinfo) {
                            var payInfoData = res.data.Orderpayinfo;
                            renderPayInfoList(payInfoData.list);

                            // 渲染分页
                            laypage.render({
                                elem: 'payinfoPage',
                                count: payInfoData.total,
                                curr: currentPage,
                                limit: pageSize,
                                layout: ['count', 'prev', 'page', 'next', 'limit'],
                                limits: [5, 10, 20, 50],
                                jump: function (obj, first) {
                                    if (!first) {
                                        currentPage = obj.curr;
                                        pageSize = obj.limit;
                                        loadPayInfos();
                                    }
                                }
                            });
                        } else {
                            var errorMsg = res ? (res.msgerr || '获取支付信息失败') : '接口返回数据异常';
                            layer.msg(errorMsg, { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.closeAll('loading');
                        console.error('请求失败:', status, error);
                        layer.msg('网络错误: ' + error, { icon: 2 });
                    }
                });
            }

            // 渲染支付信息列表
            function renderPayInfoList(payInfos) {
                var html = '';
                if (payInfos && payInfos.length > 0) {
                    payInfos.forEach(function (item) {
                        html += `
                            <tr>
                                <td>${item.payid || ''}</td>
                                <td>${item.ordernum || ''}</td>
                                <td>${item.address || ''}</td>
                                <td>${item.cakeName || item.cakename || ''}</td>
                                <td>${formatMoney(item.deliverypay)}</td>
                                <td class="money-discount">${formatMoney(item.money)}</td>
                                <td>${item.remark || '无'}</td>
                                <td>${formatMoney(item.countpay)}</td>
                                <td>
                                    <div class="action-buttons">
                                        <button class="layui-btn layui-btn-xs remark-btn" data-id="${item.payid}" data-remark="${item.remark || ''}">
                                            <i class="layui-icon">&#xe60a;</i> 备注
                                        </button>
                                        <button class="layui-btn layui-btn-xs delete-btn" data-id="${item.payid}">
                                            <i class="layui-icon">&#xe640;</i> 删除
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        `;
                    });
                } else {
                    html = '<tr><td colspan="10" style="text-align: center;">暂无数据</td></tr>';
                }
                $('#payinfoTable tbody').html(html);

                // 绑定按钮事件
                bindButtonEvents();
            }

            // 绑定按钮事件
            function bindButtonEvents() {
                // 备注按钮点击事件
                $('.remark-btn').off('click').on('click', function () {
                    var payid = $(this).data('id');
                    var remark = $(this).data('remark') || '';
                    editRemark(payid, remark);
                });

                // 删除按钮点击事件
                $('.delete-btn').off('click').on('click', function () {
                    var payid = $(this).data('id');
                    deletePayInfo(payid);
                });
            }

            // 编辑备注
            function editRemark(payid, currentRemark) {
                // 填充表单数据
                form.val('remarkForm', {
                    payid: payid,
                    remark: currentRemark
                });

                // 重置错误提示
                $('#remarkError').hide().text('');

                // 打开备注编辑对话框
                layer.open({
                    type: 1,
                    title: '修改备注 - ID: ' + payid,
                    area: ['500px', '300px'],
                    content: $('#remarkDialog'),
                    success: function () {
                        // 对话框打开后聚焦到备注文本框
                        $('.layui-textarea').focus();
                    }
                });
            }

            // 提交备注修改
            form.on('submit(remarkSubmit)', function (data) {
                updateRemarkOnly(data.field);
                return false;
            });

            // 只更新备注
            function updateRemarkOnly(formData) {
                // 验证数据
                if (!formData.payid) {
                    showRemarkError('支付ID不能为空');
                    return;
                }

                if (formData.remark && formData.remark.length > 200) {
                    showRemarkError('备注内容不能超过200个字符');
                    return;
                }

                layer.load(1);

                // 构建请求数据（表单格式）
                var requestData = {
                    payid: parseInt(formData.payid),
                    remark: formData.remark || ''
                };

                $.ajax({
                    url: 'http://localhost:8887/orderpayinfo/updateRemark',
                    type: 'POST',
                    data: requestData,  // 直接传对象
                    dataType: 'json',
                    success: function (res) {
                        layer.closeAll('loading');
                        if (res && res.code === 200) {
                            layer.msg('备注修改成功', { icon: 1 });
                            layer.closeAll();
                            loadPayInfos();
                        } else {
                            var errorMsg = res ? (res.msgerr || '修改失败') : '服务器返回异常';
                            showRemarkError(errorMsg);
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.closeAll('loading');
                        console.error('备注更新错误:', xhr.responseText);

                        let errorMsg = '网络错误';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMsg = xhr.responseJSON.message;
                        } else if (xhr.status === 400) {
                            errorMsg = '请求参数错误';
                        } else if (xhr.status === 404) {
                            errorMsg = '接口不存在';
                        }

                        showRemarkError(errorMsg);
                    }
                });
            }

            // 显示备注错误信息
            function showRemarkError(message) {
                $('#remarkError').text(message).show();
                $('.layui-textarea').focus();
            }

        
           // 删除支付信息
function deletePayInfo(payid) {
    layer.confirm('确定要删除这条支付记录吗？', {
        icon: 3,
        title: '提示'
    }, function(index) {
        layer.load(1);
        $.ajax({
            url: 'http://localhost:8887/orderpayinfo/deleteOrderpayinfo',
            type: 'POST',
            // 修改为表单格式数据
            data: { payid: payid },  // 直接传对象，不是JSON字符串
            dataType: 'json',
            success: function(res) {
                layer.closeAll();
                if (res && res.code === 200) {
                    layer.msg('删除成功', { icon: 1 });
                    // 如果是当前页最后一条数据且不是第一页，则返回上一页
                    if ($('#payinfoTable tbody tr').length === 1 && currentPage > 1) {
                        currentPage--;
                    }
                    loadPayInfos();
                } else {
                    layer.msg(res ? res.msgerr : '删除失败', { icon: 2 });
                }
            },
            error: function(xhr, status, error) {
                layer.closeAll('loading');
                console.error('删除错误:', xhr.responseText);
                layer.msg('网络错误，请稍后重试', { icon: 2 });
            }
        });
    });
}

            // 配送状态格式化
            function formatDeliveryStatus(status) {
                return status == 0 ? '可配送' : '不可配送';
            }

            // 金额格式化
            function formatMoney(amount) {
                if (amount === null || amount === undefined) return '0.00';
                return parseFloat(amount).toFixed(2);
            }

            // 搜索支付信息
            form.on('submit(searchBtn)', function (data) {
                searchParams = {
                    orderNum: data.field.orderNum,
                    address: data.field.address,
                    cakeName: data.field.cakeName
                };
                currentPage = 1;
                loadPayInfos();
                return false;
            });

            // 重置搜索
            $('#resetBtn').on('click', function () {
                searchParams = {};
                currentPage = 1;
                loadPayInfos();
            });

            // 初始化加载支付信息
            loadPayInfos();
        });
		}
    </script>
</body>

</html>